package com.example.admanagement.servlet;

import com.example.admanagement.AdService;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/deleteAd")
public class DeleteAdServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(DeleteAdServlet.class);
    private final Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");

        try {
            // 获取广告ID
            String idStr = request.getParameter("id");
            if (idStr == null || idStr.trim().isEmpty()) {
                logger.error("删除广告失败：ID为空");
                sendErrorResponse(response, "广告ID不能为空");
                return;
            }

            // 直接传递 idStr，不进行转换
            logger.info("尝试删除广告，ID: {}", idStr);

            // 调用服务删除广告
            AdService.Result<Void> result = AdService.deleteAd(idStr);

            // 创建响应对象
            Map<String, Object> jsonResponse = new HashMap<>();
            jsonResponse.put("success", result.isSuccess());
            jsonResponse.put("message", result.getMessage());
            jsonResponse.put("data", result.isSuccess());

            // 发送响应
            response.getWriter().write(gson.toJson(jsonResponse));

        } catch (Exception e) {
            logger.error("删除广告时发生错误", e);
            sendErrorResponse(response, "删除广告时发生错误：" + e.getMessage());
        }
    }

    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        Map<String, Object> jsonResponse = new HashMap<>();
        jsonResponse.put("success", false);
        jsonResponse.put("message", message);
        jsonResponse.put("data", false);
        response.getWriter().write(gson.toJson(jsonResponse));
    }
}